package com.kinon.ceshiaccount.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.bean.UrlBean;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.home.BalanceFragment;
import com.kinon.ceshiaccount.fragment.home.CardTakeMealFragment;
import com.kinon.ceshiaccount.fragment.home.FingerEatFragment;
import com.kinon.ceshiaccount.fragment.home.LunchFragment;
import com.kinon.ceshiaccount.fragment.home.MenuFragment;
import com.kinon.ceshiaccount.fragment.home.OrderFragment;
import com.kinon.ceshiaccount.fragment.home.RecordFragment;
import com.kinon.ceshiaccount.fragment.home.SetFragment;
import com.kinon.ceshiaccount.fragment.home.SettlementFragment;
import com.kinon.ceshiaccount.fragment.home.TakeMealFragment;
import com.kinon.ceshiaccount.fragment.home.TieFingerFragment;
import com.kinon.ceshiaccount.fragment.home.TiedCardFragment;
import com.kinon.ceshiaccount.fragment.home.WxpayFragment;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.CustomDialog;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import static com.kinon.ceshiaccount.constant.Constant.URGENT_TYPE;

//import com.kinon.ceshiaccount.fragment.home.FingerEatFragment;

//import android.util.Log;

/**
 * app主界面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private RadioButton rb_settlement;
    private RadioButton rb_lunch;
//    private RadioButton rb_dinner;
    private RadioButton rb_takeMeal;
    private RadioButton rb_record;
    private RadioButton rb_order;
    //微信支付
    private RadioButton rb_wxpay;
    //绑卡
    private RadioButton rb_tiedCard;
    //绑指纹
    private RadioButton rb_tieFinger;
    //刷卡取餐
    private RadioButton rb_cardTake;
    //指纹就餐
    private RadioButton rb_fingerEat;
    private RadioButton rb_set;
    private RadioButton rb_menu;
    private RadioButton rb_balance;
//    private RadioButton rbs [];
//    private String
    /**显示时间*/
    private TextView tv_time;
    /**显示是紧急状态*/
    private TextView tv_uhint;
    private TextView tv_company;

    private ArrayList<Fragment> fragments=new ArrayList<Fragment>();
    private FragmentManager fm;
    private int currentItem=12;
    //是否结束线程
    private boolean isEndHander=false;
    ArrayList<Integer> functions=new ArrayList<Integer>();

    //自定义广播
    private UrgentBroadcastReceiver broadcast=new UrgentBroadcastReceiver();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        registerBroadcast();
    }

    private void initView() {

        rb_settlement= (RadioButton) findViewById(R.id.rb_settlement);
        rb_lunch= (RadioButton) findViewById(R.id.rb_lunch);
        rb_takeMeal= (RadioButton) findViewById(R.id.rb_takeMeal);
        rb_record= (RadioButton) findViewById(R.id.rb_record);
        rb_order= (RadioButton) findViewById(R.id.rb_order);
        rb_set= (RadioButton) findViewById(R.id.rb_set);
        rb_wxpay= (RadioButton) findViewById(R.id.rb_wxpay);
        rb_tiedCard= (RadioButton) findViewById(R.id.rb_tiedCard);
        rb_tieFinger= (RadioButton) findViewById(R.id.rb_tieFinger);
        rb_cardTake= (RadioButton) findViewById(R.id.rb_cartTake);
        rb_fingerEat= (RadioButton) findViewById(R.id.rb_fingerEat);
        rb_menu= (RadioButton) findViewById(R.id.rb_menu);
        rb_balance= (RadioButton) findViewById(R.id.rb_balance);
        tv_time= (TextView) findViewById(R.id.tv_time);
        tv_uhint= (TextView) findViewById(R.id.tv_uhint);
        tv_company= (TextView) findViewById(R.id.tv_company);

        String strurl= SPManage.getInstance().getString("urlbean");
        Log.e(TAG, "urlbean=== "+strurl);

        Gson gson=new Gson();
        if(!TextUtils.isEmpty(strurl)){
            UrlBean urlBean=gson.fromJson(strurl,UrlBean.class);
            if(urlBean.getApp_function()!=null ||urlBean.getApp_function().size()>0){
                functions.addAll(urlBean.getApp_function());
            }
            if(!TextUtils.isEmpty(urlBean.getName())){
                tv_company.setText(urlBean.getName());
            }
        }


//        rbs =new RadioButton[]{rb_settlement,rb_lunch,rb_takeMeal,
//                rb_record,rb_order,rb_set,rb_wxpay,rb_tiedCard};

        //判断是否是紧急模式
        if(URGENT_TYPE){
            tv_uhint.setVisibility(View.VISIBLE);
        }else{
            //显示是否要
            showDataSubmitDialog();
        }
        //显示需要的功能
        showIcom();
//        for(int i:functions){
//            rbs[i-1].setVisibility(View.VISIBLE);
//
//        }

        new TimeThread().start();

        addListFragment();
        setAddOnclick();

    }

    private void showIcom(){
        rb_balance.setVisibility(View.VISIBLE);
//        for(int i:functions){
//            if(i==1){
//                rb_settlement.setVisibility(View.VISIBLE);
//            }else if(i==2){
//                rb_lunch.setVisibility(View.VISIBLE);
//
//            }else if(i==3){
//                rb_takeMeal.setVisibility(View.VISIBLE);
//
//            }else if(i==4){
//                rb_record.setVisibility(View.VISIBLE);
//
//            }else if(i==5){
//                rb_order.setVisibility(View.VISIBLE);
//
//            }else if(i==6){
//                rb_set.setVisibility(View.VISIBLE);
//
//            }else if(i==26){
//                rb_wxpay.setVisibility(View.VISIBLE);
//
//            }else if(i==27){
//                rb_tiedCard.setVisibility(View.VISIBLE);
//
//            }else if(i==28){
//                rb_tieFinger.setVisibility(View.VISIBLE);
//            }else if(i==29){
//                rb_cardTake.setVisibility(View.VISIBLE);
//            }else if(i==32){
//                rb_fingerEat.setVisibility(View.VISIBLE);
//            }else if(i==34){
//                rb_menu.setVisibility(View.VISIBLE);
//            }else if(i==37){
//                rb_balance.setVisibility(View.VISIBLE);
//            }
//
//        }
    }

    /**
     * 注册广播方法
     */
    private void registerBroadcast() {
        //表名接收广播类型
        IntentFilter filter =
                new IntentFilter(UrgentSetActivity.LOGIN_ACTION);
        LocalBroadcastManager.getInstance(getApplicationContext())
                .registerReceiver(broadcast, filter);
    }
    /**
     * 销毁广播，避免内存泄漏
     */
    private void unregisterBroadcast(){
        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(broadcast);
    }

    /**
     * 将fragment加入集合,并且显示第一个fragment
     */
    private void addListFragment(){
        fragments.add(new SettlementFragment());
        fragments.add(new LunchFragment());
        fragments.add(new TakeMealFragment());
        fragments.add(new RecordFragment());
        fragments.add(new OrderFragment());
        fragments.add(new SetFragment());
        fragments.add(new WxpayFragment());
        fragments.add(new TiedCardFragment());
        fragments.add(new TieFingerFragment());
        fragments.add(new CardTakeMealFragment());
        fragments.add(new FingerEatFragment());
        fragments.add(new MenuFragment());
        fragments.add(new BalanceFragment());

        showFirsetFragment();
    }

    private void removeItem(){
        for(int j:functions) {
            boolean ishas=false;
            int position=-1;
            for (int i = 0; i < fragments.size(); i++) {
                if (i == (j-1)) {
                    ishas=true;
                }
                position=i;
            }
            if(!ishas || position==-1){
                fragments.remove(position);
            }
        }
    }

    /**
     * 绑定按钮的点击事件监听
     */
    private void setAddOnclick(){
        rb_settlement.setOnClickListener(this);
        rb_lunch.setOnClickListener(this);
        rb_takeMeal.setOnClickListener(this);
        rb_record.setOnClickListener(this);
        rb_order.setOnClickListener(this);
        rb_wxpay.setOnClickListener(this);
        rb_set.setOnClickListener(this);
        rb_tiedCard.setOnClickListener(this);
        rb_tieFinger.setOnClickListener(this);
        rb_cardTake.setOnClickListener(this);
        rb_fingerEat.setOnClickListener(this);
        rb_menu.setOnClickListener(this);
        rb_balance.setOnClickListener(this);

    }

    /**
     * 显示首页的fragment
     */
    private void showFirsetFragment(){
        fm=getSupportFragmentManager();
        //开启fragment的事务
        FragmentTransaction ftransaction=fm.beginTransaction();
        ftransaction.add(R.id.fl_home,fragments.get(currentItem));
        ftransaction.show(fragments.get(currentItem));
        ftransaction.commit();
   }

    /**
     * 加载显示fragment
     */
   private void showFragment(int position){
       if(currentItem!=position){
           FragmentTransaction ftransaction=fm.beginTransaction();
           //隐藏之间显示的fragment
           ftransaction.hide(fragments.get(currentItem));
           //判断fragment是否加载过，
           if(!fragments.get(position).isAdded()){
               ftransaction.add(R.id.fl_home,fragments.get(position));
           }
           ftransaction.show(fragments.get(position));
           ftransaction.commit();
           currentItem=position;
       }

   }

   private class TimeThread extends Thread{
       @Override
       public void run() {
           super.run();
           while (!isEndHander){
               try {
                   Message msg=new Message();
                   msg.what= Constant.TIME_THREAD_MESSAGE;
                   TimeHandler.sendMessage(msg);

                   Thread.sleep(Constant.TIME_THREAD_SLEEP);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       }
   };


   private Handler TimeHandler=new Handler(){
       @Override
       public void handleMessage(Message msg) {
           super.handleMessage(msg);
           switch (msg.what){
               case Constant.TIME_THREAD_MESSAGE:
                   long sysTime=System.currentTimeMillis();
                   CharSequence timeStr= DateFormat.format("HH:mm:ss", sysTime);
                   tv_time.setText(timeStr);
                   break;
           }
       }
   };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadcast();
        isEndHander=true;

    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rb_settlement:
                showFragment(0);
                break;
            case R.id.rb_lunch:
                showFragment(1);
                break;
            case R.id.rb_takeMeal:
                showFragment(2);
                break;
            case R.id.rb_record:
                showFragment(3);
            break;case R.id.rb_order:
                showFragment(4);
                break;
            case R.id.rb_set:
                showFragment(5);
                break;
            case R.id.rb_wxpay:
                showFragment(6);
                break;
            case R.id.rb_tiedCard:
                showFragment(7);
                break;
            case R.id.rb_tieFinger:
                showFragment(8);
                break;
            case R.id.rb_cartTake:
                showFragment(9);
                break;
            case R.id.rb_fingerEat:
                showFragment(10);
                break;
            case R.id.rb_menu:
                showFragment(11);
                break;
            case R.id.rb_balance:
                showFragment(12);
                break;

        }
    }

    //提示有离线数据弹窗
    private void showDataSubmitDialog(){
        int num= DataSupport.where("submit = ?","0").count(U_SettletmentBean.class);
        if(num<=0){
            return;
        }
        CustomDialog dialog=new CustomDialog(MainActivity.this, "有离线数据是否马上去提交",
                new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                if(btn==1){
                    Intent intent=new Intent(getApplicationContext(),UrgentSetActivity.class);
                    startActivity(intent);
                }
            }
        });
        dialog.show();
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Mtoast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private  class  UrgentBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(!Constant.URGENT_TYPE){
                tv_uhint.setVisibility(View.GONE);
            }else{
                tv_uhint.setVisibility(View.VISIBLE);
            }
        }
    }
}
